import { Loading } from 'element-ui'
import Vue from 'vue'
import VueRouter from 'vue-router'
import { setTitle } from '../common/utils'
import { routers } from './route'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) 
{
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}


const routerConfig = {
  mode: 'history',
  base: process.env.BASE_URL,
  linkActiveClass: 'active',
  routes: routers
}

const router = new VueRouter(routerConfig)

let loading
router.beforeEach((to, _form, next) => {
  loading = Loading.service({
    // fullscreen: true,
    target: '.content-wrapper',
    text: '跳转中...'
  })

  // 设置window.document.title 的名称
  setTitle(to.meta.title)

  if (!to.matched.length) {
    next({
      path: '/error/404',
      replace: true
    })
  } else {
    next()
  }
})

router.afterEach(() => {
  // 解决某些情况下loading无法关闭的情况
  setTimeout(() => {
    loading.close()
  }, 0)
})

export default router
